/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package File;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DB.DBConnectionJm;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.sql.ResultSet;
import javax.servlet.ServletOutputStream;

/**
 *
 * @author Tiong Jia Ming
 */
public class FileDownload extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private String path = "";
    private String extension = "";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext context = this.getServletContext();
        Scribd scribd = new Scribd();
        try {
            try {
                String filename = request.getParameter("fileName");
                //APPLICATION/OCTET-STREAM will tell the browser to prompt the user to save the file
                DBConnectionJm dbc = new DBConnectionJm();
                dbc.setQuery("Select * from FileRecords where FileScribdID = ?;");
                dbc.setAttributes(new String[]{request.getParameter("fileID").toString()});
                ResultSet rs = dbc.doQuery();
                while (rs.next()) {
                    path = rs.getString("FileLocation");
                    dbc.setUpdate("UPDATE FileRecords set FileDownloads = ? where FileID = ?;");
                    int downloads = rs.getInt("FileDownloads") + 1;
                    dbc.setAttributes(new String[]{Integer.toString(downloads), rs.getString("FileID")});
                    dbc.doUpdate();
                }
                try {
                    String file = new File(path).getName();
                    int index = file.indexOf(".");
                    extension = file.substring(index + 1);
                    FileContentType FCT = new FileContentType();
                    String contentType = "";
                    if (extension.equalsIgnoreCase("pdf")) {
                        contentType = FCT.getPdf();
                    } else if (extension.equalsIgnoreCase("xls")) {
                        contentType = FCT.getExcel();
                    } else if (extension.equalsIgnoreCase("xml")) {
                        contentType = FCT.getXml();
                    } else if (extension.equalsIgnoreCase("doc")) {
                        contentType = FCT.getDoc();
                    } else {
                        contentType = FCT.getText();
                    }
                    String link = scribd.getScribdURL(extension, request.getParameter("fileID").toString());
                    DownloadDoc(response, link, filename, contentType);
                } catch (Exception ex) {
                    System.out.println(ex);
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void DownloadDoc(HttpServletResponse response, String link, String filename, String contentType) throws Exception {
        PrintWriter out = response.getWriter();
        response.reset();
        response.setContentType(contentType);
        String disHeader = "Attachment;Filename =\"" + filename + "\"";
        response.setHeader("Content-Disposition", disHeader);
        URL u = new URL(link);
        InputStream is = u.openStream();
        URLConnection con = u.openConnection();
        DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
        BufferedReader br1 = new BufferedReader(new InputStreamReader(dis));
        byte[] fileData;
        fileData = new byte[con.getContentLength()]; // determine how many byes the file size is and make array big enough to hold the data
        for (int x = 0; x < fileData.length; x++) { // fill byte array with bytes from the data input stream
            fileData[x] = dis.readByte();
        }
        FileOutputStream fos = new FileOutputStream(new File("temp.pdf"));  //create an object representing the file we want to save
        fos.write(fileData);
        fos.close();
        File fileToDownload = new File("temp.pdf");
        FileInputStream fileInputStream = new FileInputStream(fileToDownload);
        int i = 0;
        while ((i = fileInputStream.read()) != -1) {
            // sending the file to the client
            out.write(i);
        }
        fileInputStream.close();
        br1.close();
        dis.close();
        is.close();
    }
}
